//  wechat-api instance
(function() {
  var WXApi, appId, appSecret, config, getToken, log4js, logger, redisClient, saveToken, urllib, wxapi;

  WXApi = require('wechat-api');

  config = require('config');

  urllib = require('urllib');

  log4js = require('log4js');

  redisClient = require('./redis');

  appId = config.wechat.appid;

  appSecret = config.wechat.appsecret;

  logger = log4js.getLogger('wxapi');


  /*
   * 获取全局token的方法
   * 尝试从redis中获取token
   */

  getToken = function(callback) {
    return redisClient.get('wx_mp_access_token', function(err, reply) {
      if (err) {
        return callback(err);
      } else {
        return callback(null, reply);
      }
    });
  };


  /*
   * 保存token到redis缓存中
   */

  saveToken = function(token, callback) {
    redisClient.set('wx_mp_access_token', token);
    redisClient.expire('wx_mp_access_token', 7000);
    return callback(null);
  };

  wxapi = new WXApi(appId, appSecret, getToken, saveToken);

  module.exports = wxapi;

}).call(this);
